package com.ruoyi.htgl.htbg.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.activiti.service.MyTaskService;
import com.ruoyi.activiti.vo.HistoryVo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.WordUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.htgl.htbg.domain.HtglHtbgFj;
import com.ruoyi.htgl.htbz.domain.HtglHtbzNdjh;
import com.ruoyi.infoRunTaskData.domain.InfoRunTaskData;
import com.ruoyi.infoRunTaskData.service.IInfoRunTaskDataService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.htgl.htbg.domain.HtglHtbg;
import com.ruoyi.htgl.htbg.service.IHtglHtbgService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 合同变更Controller
 *
 * @author huacai
 * @date 2024-07-25
 */
@RestController
@RequestMapping("/htbg/htbg")
public class HtglHtbgController extends BaseController
{
    @Resource
    private IHtglHtbgService htglHtbgService;

    @Resource
    private IInfoRunTaskDataService iInfoRunTaskDataService;

    @Resource
    private MyTaskService myTaskService;

    /**
     * 查询合同变更列表
     */
    @PreAuthorize("@ss.hasPermi('htbg:htbg:list')")
    @GetMapping("/list")
    public TableDataInfo list(HtglHtbg htglHtbg)
    {
        startPage();
        List<HtglHtbg> list = htglHtbgService.selectHtglHtbgList(htglHtbg);
        return getDataTable(list);
    }

    /**
     * 导出合同变更列表
     */
    @PreAuthorize("@ss.hasPermi('htbg:htbg:export')")
    @Log(title = "合同变更", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HtglHtbg htglHtbg)
    {
        List<HtglHtbg> list = htglHtbgService.selectHtglHtbgList(htglHtbg);
        ExcelUtil<HtglHtbg> util = new ExcelUtil<HtglHtbg>(HtglHtbg.class);
        util.exportExcel(response, list, "合同变更数据");
    }

    /**
     * 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<HtglHtbg> util = new ExcelUtil<HtglHtbg>(HtglHtbg.class);
        util.importTemplateExcel(response, "合同变更数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "合同变更", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('htbg:htbg:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<HtglHtbg> util = new ExcelUtil<HtglHtbg>(HtglHtbg.class);
        InputStream inputStream = file.getInputStream();
        List<HtglHtbg> list = util.importExcel(inputStream );
        inputStream.close();
        int count = htglHtbgService.batchInsertHtglHtbg(list);
        return AjaxResult.success("导入成功" + count + "条信息！");
    }

    /**
     * 获取合同变更详细信息
     */
    @PreAuthorize("@ss.hasPermi('htbg:htbg:query')")
    @GetMapping(value = "/{htbgId}")
    public AjaxResult getInfo(@PathVariable("htbgId") String htbgId)
    {
        return success(htglHtbgService.selectHtglHtbgByHtbgId(htbgId));
    }

    /**
     * 获取合同变更与组成人员详细信息
     */
    @PreAuthorize("@ss.hasPermi('htbg:htbg:query')")
    @GetMapping(value = "/zcry/{htbgId}")
    public AjaxResult selectHtglHtbgZcryByHtbgId(@PathVariable("htbgId") String htbgId) {
        return success(htglHtbgService.selectHtglHtbgZcryByHtbgId(htbgId));
    }

    /**
     * 新增合同变更
     */
    @PreAuthorize("@ss.hasPermi('htbg:htbg:add')")
    @Log(title = "合同变更", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HtglHtbg htglHtbg) {
        htglHtbg.setUserId(Math.toIntExact(getUserId()));
        int i = htglHtbgService.insertHtglHtbg(htglHtbg);
        //向流程业务表中加入数据
        InfoRunTaskData infoRunTaskData = new InfoRunTaskData();
        infoRunTaskData.setBusinessKey(htglHtbg.getHtbgId());
        infoRunTaskData.setBusinessType(5); //业务模块: 合同管理-变更管理
        infoRunTaskData.setBusinessTitle(htglHtbg.getHtName()); //任务名称: 合同名称
        infoRunTaskData.setApplyUser(SecurityUtils.getLoginUser().getUser().getNickName());//申请人

        iInfoRunTaskDataService.insertInfoRunTaskData(infoRunTaskData);
        return toAjax(i);
    }

    /**
     * 修改合同变更
     */
    @PreAuthorize("@ss.hasPermi('htbg:htbg:edit')")
    @Log(title = "合同变更", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HtglHtbg htglHtbg) {
        //修改业务中间表关系数据
        InfoRunTaskData infoRunTaskData = new InfoRunTaskData();
        infoRunTaskData.setBusinessTitle(htglHtbg.getHtName()); //任务名称: 合同名称
        infoRunTaskData.setBusinessKey(htglHtbg.getHtbgId());
        infoRunTaskData.setBusinessType(5); //业务模块: 合同管理-变更管理
        iInfoRunTaskDataService.updateInfoRunTaskDatas(infoRunTaskData); //注意updateInfoRunTaskDatas

        return toAjax(htglHtbgService.updateHtglHtbg(htglHtbg));
    }

    /**
     * 删除合同变更
     */
    @PreAuthorize("@ss.hasPermi('htbg:htbg:remove')")
    @Log(title = "合同变更", businessType = BusinessType.DELETE)
	@DeleteMapping("/{htbgIds}")
    public AjaxResult remove(@PathVariable String[] htbgIds) {
        //同时删除业务关系数据
        for (String htbgId : htbgIds) {
            HtglHtbg htglHtbg = htglHtbgService.selectHtglHtbgByHtbgId(htbgId);
            iInfoRunTaskDataService.deleteData(htglHtbg.getHtbgId(), 5);//业务模块: 人才平台-人员申请
        }
        return toAjax(htglHtbgService.deleteHtglHtbgByHtbgIds(htbgIds));
    }

    /**
     * 获得合同变更ID
     */
    @GetMapping("/getHtBgId")
    public AjaxResult getHtBgId(){
        String htBgId = IdUtils.fastSimpleUUID();
        return success(htBgId);
    }

    /**
     * 新增附件
     */
    @PostMapping("/add/File/By/subId")
    public AjaxResult insertHtbgFjByHtbgId(@RequestBody HtglHtbgFj htglHtbgFj) {
        return toAjax(htglHtbgService.insertHtbgFjByHtbgId(htglHtbgFj));
    }

    /**
     * 根据ID查询附件列表
     */
    @GetMapping("/get/FileList/By/subId")
    public AjaxResult selectHtbgFjList(String sId){
        HtglHtbgFj htglHtbgFj = new HtglHtbgFj();
        htglHtbgFj.setHtbgId(sId);
        return AjaxResult.success(htglHtbgService.selectHtbgFjList(htglHtbgFj));
    }

    /**
     * 删除合同变更附件
     */
    @Log(title = "合同变更附件", businessType = BusinessType.DELETE)
    @DeleteMapping("/fj/{fjIds}")
    public AjaxResult remove(@PathVariable Integer[] fjIds)
    {
        return toAjax(htglHtbgService.deleteHtglHtbgFjByFjIds(fjIds));
    }

    /**
     * 根据模板导出word
     * @param response
     * @return
     */
    @Log(title = "根据模板导出word", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('occupation:basics:exportWord')")
    @GetMapping("/exportWord/{htbgId}")
    public AjaxResult exportWord(@PathVariable("htbgId") String htbgId, HttpServletRequest request, HttpServletResponse response) {
        HtglHtbg htglHtbg = htglHtbgService.selectHtglHtbgByHtbgId(htbgId);
        String htName = htglHtbg.getHtName(); //合同名称
        String htBh = htglHtbg.getHtBh(); //合同编号

        //获取申请日期
        Date sqTime = htglHtbg.getSqTime();
        // 使用 Calendar 提取年、月、日
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sqTime);
        int year = calendar.get(Calendar.YEAR); //年
        int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以要加1
        int day = calendar.get(Calendar.DAY_OF_MONTH); //日

        String sqDw = htglHtbg.getSqDw(); //申请单位
        String lxPhone = htglHtbg.getLxPhone(); //联系电话

        // 创建一个 SimpleDateFormat 对象，指定日期格式
        SimpleDateFormat sdfYM = new SimpleDateFormat("yyyy-MM");
        Date getyQTime = htglHtbg.getyQTime(); //项目起时间
        String qTime = sdfYM.format(getyQTime); // 使用 SimpleDateFormat 对象将 Date 对象格式化为 String 对象
        Date getyZTime = htglHtbg.getyZTime(); //项目止时间
        String zTime = sdfYM.format(getyZTime); // 使用 SimpleDateFormat 对象将 Date 对象格式化为 String 对象

        //申请变更事项
        String sqBgSx = htglHtbg.getSqBgSx(); //申请变更事项
        String jf = "□"; //经费
        String ktFzr = "□"; //课题负责人
        String xmzCy = "□"; //项目组成员
        String yq = "□"; //延期
        String mcBg = "□"; //名称变更

        // 检查字符串是否包含逗号
        if (sqBgSx.contains(",")) {
            // 使用逗号分隔字符串并存储到数组中
            String[] numbers = sqBgSx.split(",");
            // 检查数组中是否包含各个数字
            if (Arrays.asList(numbers).contains("经费")) {
                jf = "☑";
            }
            if (Arrays.asList(numbers).contains("课题负责人")) {
                ktFzr = "☑";
            }
            if (Arrays.asList(numbers).contains("项目组成员")) {
                xmzCy = "☑";
            }
            if (Arrays.asList(numbers).contains("延期")) {
                yq = "☑";
            }
            if (Arrays.asList(numbers).contains("名称变更")) {
                mcBg = "☑";
            }
        } else {
            // 直接检查字符串是否等于各个数字
            if (sqBgSx.equals("经费")) {
                jf = "☑";
            }
            if (sqBgSx.equals("课题负责人")) {
                ktFzr = "☑";
            }
            if (sqBgSx.equals("项目组成员")) {
                xmzCy = "☑";
            }
            if (sqBgSx.equals("延期")) {
                yq = "☑";
            }
            if (sqBgSx.equals("名称变更")) {
                mcBg = "☑";
            }
        }

        String bgYy = htglHtbg.getBgYy(); //变更原因
        String bgNr = htglHtbg.getBgNr(); //变更内容
        String zxSm = htglHtbg.getZxSm(); //变更事项执行时间说明

        List<HistoryVo> spLcList = myTaskService.selectHistory(htglHtbg.getProcessInstanceId()); //审批流程列表
        String lcListToHtml = " "; //审批流程(转成需要的格式)
        if (spLcList.size() == 0){
            lcListToHtml = "未提交审批";
        }else {
            lcListToHtml = spLcListToHtml(spLcList); //审批流程(转成需要的格式)
        }

        Map<String, Object> map = new HashMap<>();

        map.put("htName", htName);
        map.put("htBh", htBh);
        map.put("year", year);
        map.put("month", month);
        map.put("day", day);
        map.put("sqDw", sqDw);
        map.put("lxPhone", lxPhone);
        map.put("qTime", qTime);
        map.put("zTime", zTime);

        map.put("jf", jf); //经费
        map.put("ktFzr", ktFzr); //课题负责人
        map.put("xmzCy", xmzCy); //项目组成员
        map.put("yq", yq); //延期
        map.put("mcBg", mcBg); //名称变更

        map.put("bgYy", bgYy); //变更原因
        map.put("bgNr", bgNr); //变更内容
        map.put("zxSm", zxSm); //变更事项执行时间说明
        map.put("lcListToHtml", lcListToHtml); //审批流程

        String str = htName + ".docx";
        //获取yml配置地址
        String tempDir = RuoYiConfig.getProfile() + "/upload/";
        String name = WordUtil.easyPoiExport("static/word/htbg/htbg.docx", tempDir, str, map, request, response);
        return AjaxResult.success(name);
    }

    /**
     * 审批流程 生成 html
     */
    private String spLcListToHtml(List<HistoryVo> spLcList) {
        String resultStr = "";
//        1、2021-11-24 16:13:01 一水科管 开始编制
//        2、2021-11-24 16:37:02 一水科管 一水科管提交审批
//        3、2021-11-24 16:45:35 G060101 分局审批-退回
//        4、2021-11-24 17:00:52 一水科管 重新提交审批 重新提交审批
//        5、2021-11-25 13:52:39 G060101 分局审批-审核通过
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 1; i <= spLcList.size(); i++) {
            HistoryVo historyVo = spLcList.get(i - 1);
            String zxTime = simple.format(historyVo.getEndTime()); //执行时间
            String nickName = historyVo.getNickName(); //执行人
            String taskName = historyVo.getTaskName(); //节点名称
            resultStr += i + "、" + zxTime + " " + nickName + " " + taskName + "\r";
        }
        return resultStr;
    }

}
